<?php
/**
 * Created by PhpStorm.
 * User: 小灰灰
 * Date: 2023-02-22
 * Time: 16:41:58
 * Info:
 */

namespace app\admin\controller;

use think\facade\View;
use app\common\model\Models as ModModels;
use app\common\model\Content as ContentModels;
use app\common\model\Category as CategoryModel;
use app\common\model\CategoryChildid as CategoryChildidModel;
use libs\Pinyin;

class Category extends Base
{

    /**
     * 列表
     * @return string
     */
    public function index()
    {
        $params = [];
        //判断是否是ajax发送方式
        if ($this->request->isAjax()) {
            $params['limit'] = (int)input('limit', 10);
            $params['page']  = (int)input('page', 1);
            $params['first'] = ($params['page'] - 1) * $params['limit'];
            $params['field'] = input('field', 'id');
            $params['order'] = input('order', 'asc');
            $data            = CategoryModel::getCategoryList($params);
            $this->success('ok', $data['list'], $data['count']);
        }

        return View::fetch();
    }

    /**
     * 添加
     * @return string
     * @throws \think\db\exception\DbException
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            if (empty($param['model_id'])) {
                $this->error('请选择所属模型');
            }
            if (empty($param['name'])) {
                $this->error('栏目名称不能为空');
            }
            if ( ! empty($param['index_tpl'])) {
                $param['index_tpl'] = explode('.', $param['index_tpl'])[0];
            }
            if ($param['model_id'] != 2) {
                if (empty($param['list_tpl'])) {
                    $this->error('列表模板不能为空');
                }
                if (empty($param['show_tpl'])) {
                    $this->error('内容模板不能为空');
                }
            }
            if ( ! empty($param['list_tpl'])) {
                $param['list_tpl'] = explode('.', $param['list_tpl'])[0];
            }
            if ( ! empty($param['show_tpl'])) {
                $param['show_tpl'] = explode('.', $param['show_tpl'])[0];
            }
            if ( ! empty($param['dirname'])) {
                //如果目录名称不为空，查询是否有重复
                $isName = CategoryModel::where(['dirname' => $param['dirname']])->count();
                if ($isName) {
                    $this->error('该目录名称已存在,不允许重名');
                }
            } else {
                //目录名称为空，生成字母+随机数字
                $pinyin           = new PinYin();
                $all_py           = $pinyin->get_all_py($param['name']);
                $param['dirname'] = join('', $all_py).'_'.mt_rand(100, 999);
            }
            $res = CategoryModel::create($param);
            //更新父级栏目的子级字段
            (new CategoryChildidModel)->manageData($param['pid'], $res->id);
            //如果是单页模型-添加对应栏目的内容
            if ($param['model_id'] == 2) {
                $contentData = [
                    'model_id' => $param['model_id'],
                    'cate_id'  => $res->id,
                    'title'    => $param['name'],
                    'admin_id' => cmf_get_admin_id()
                ];
                ContentModels::create($contentData);
            }

            $this->success('操作成功');
        }
        //模型下拉
        $model_id     = (int)input('get.model_id');
        $modelsIdList = ModModels::getModelsIdMenuList();
        $cates        = (new CategoryModel())->getPidCategoryList(true);

        View::assign('cates', $cates);
        View::assign('model_id', $model_id);
        View::assign('modelsIdList', $modelsIdList);

        return View::fetch();
    }

    /**
     * 修改
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function edit()
    {
        if ($this->request->isPost()) {
            //获取序列化数据
            $param = self::input();
            if (empty($param['id'])) {
                $this->error('参数错误');
            }
            if ( ! empty($param['index_tpl'])) {
                $param['index_tpl'] = explode('.', $param['index_tpl'])[0];
            }
            if ( ! empty($param['list_tpl'])) {
                $param['list_tpl'] = explode('.', $param['list_tpl'])[0];
            }
            if ( ! empty($param['show_tpl'])) {
                $param['show_tpl'] = explode('.', $param['show_tpl'])[0];
            }

            if ( ! empty($param['dirname'])) {
                //如果目录名称不为空，查询是否有重复
                $isName = CategoryModel::where('id', '<>', $param['id'])->where('dirname', $param['dirname'])->count();
                if ($isName) {
                    $this->error('该目录名称已存在,不允许重名');
                }
            } else {
                //目录名称为空，生成字母+随机数字
                $pinyin           = new PinYin();
                $all_py           = $pinyin->get_all_py($param['name']);
                $param['dirname'] = join('', $all_py).'_'.mt_rand(100, 999);
            }
            //赋值tablename
            CategoryModel::update($param, ['id' => $param['id']]);

            //更新父级栏目的子级字段
            (new CategoryChildidModel)->manageData($param['pid'], $param['id']);
            $this->success('操作成功');
        }
        $id                = input('get.id');
        $data              = CategoryModel::find($id);
        $data['index_tpl'] = $data['index_tpl'] ? $data['index_tpl'].'.html' : '';
        $data['list_tpl']  = $data['list_tpl'] ? $data['list_tpl'].'.html' : '';
        $data['show_tpl']  = $data['show_tpl'] ? $data['show_tpl'].'.html' : '';
        View::assign('data', $data);
        //模型下拉
        $model_id     = (int)input('get.model_id');
        $modelsIdList = ModModels::getModelsIdMenuList();
        $cates        = (new CategoryModel())->getPidCategoryList(true);

        View::assign('cates', $cates);
        View::assign('model_id', $model_id);
        View::assign('modelsIdList', $modelsIdList);

        return View::fetch();
    }

    /**
     * 修改状态
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function modify()
    {
        if ($this->request->isAjax()) {
            if (empty(input('get.id')) || empty(input('get.field'))) {
                $this->error('参数错误');
            }
            $param[input('get.field')] = input('val');
            $param['id']               = input('get.id');
            CategoryModel::update($param, ['id' => $param['id']]);
            $this->success('操作成功');
        }
    }

    /**
     * 删除
     * @return void
     */
    public function delete()
    {
        if ($this->request->isAjax()) {
            $id = (int)input('get.id');
            if (empty($id)) {
                $this->error("参数错误");
            }
            $data = CategoryModel::find($id);
            if (empty($data)) {
                $this->success('该数据已删除');
            }
            //如果是单页模型，同时删除对应模型栏目下的文章
            if ($data['model_id'] == 2) {
                ContentModels::destroy(function ($query) use ($id) {
                    $query->where(['model_id' => 2, 'cate_id' => $id]);
                }, true);
            }
            //删除父级栏目的子级字段
            try {
                (new CategoryChildidModel)->manageData(0, $id);
            } catch (\Exception $e) {

            }

            CategoryModel::destroy($id);
            $this->success("删除成功");
        }
    }

    /**
     * 模型对应模版名称
     */
    public function tpl_name()
    {
        $model_id    = $this->request->param('model_id');
        $model_alias = (new ModModels())->getModelAlias($model_id);

        //获取后台设置的模版文件夹：
        $themePath = get_template_path();
        $tempArr   = glob($themePath.'*');
        $tplNames  = [];
        foreach ($tempArr as $key => $value) {
            unset($tplNames[$key]['index.html']);
            $tplNames[] = str_replace($themePath, "", $value);
        }
        $tplName = preg_grep('/^'.preg_quote($model_alias, '/').'/', $tplNames);
        $tplName = array_values($tplName);
        $this->success('获取成功', $tplName);
    }

}
